package com.songshuai.webapi.login.service.impl;

import com.songshuai.webapi.common.redis.RedisUtil;
import com.songshuai.webapi.login.client.AuthServiceClient;
import com.songshuai.webapi.login.dto.JWT;
import com.songshuai.webapi.login.dto.LoginDTO;
import com.songshuai.webapi.login.dto.RespDTO;
import com.songshuai.webapi.login.dto.UserLoginDto;
import com.songshuai.webapi.login.model.YxUsers;
import com.songshuai.webapi.login.service.LoginService;
import com.songshuai.webapi.login.utils.RegexUtil;
import com.songshuai.webapi.login.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Service
public class LoginServiceImpl extends BaseLoginService implements LoginService {



    @Resource
    AuthServiceClient authServiceClient;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.application.name}")
    String application;

    @Override
    public RespDTO createUser(UserLoginDto user) {
        int integer = RegexUtil.validPhoneOrMail(user.getUsername());
        Example example=new Example(YxUsers.class);
        YxUsers yxUsers=new YxUsers();
        Example.Criteria criteria = example.createCriteria();
        if(1==integer){//电话
            criteria.andEqualTo("mobile",user.getUsername());
            List<YxUsers> users = usersMapper.selectByExample(example);
            if(users.size()>0){
                return RespDTO.onFail("电话号码已被注册");
            }
            yxUsers.setMobile(user.getUsername());
        }else if(2==integer){//email
            criteria.andEqualTo("email",user.getUsername());
            List<YxUsers> users = usersMapper.selectByExample(example);
            if(users.size()>0){
                return RespDTO.onFail("邮件已被注册");
            }
            yxUsers.setEmail(user.getUsername());
        }else{
          return  RespDTO.onFail("用户名格式不正确");
        }
        String entryPassword = Util.md5(user.getPassword());
        yxUsers.setPassword(entryPassword);
        int i = usersMapper.insertSelective(yxUsers);
        if (i>0){
            return RespDTO.onSuc(user);
        }else{
            return RespDTO.onFail("保存用户异常");
        }
    }

    @Override
    public RespDTO login(UserLoginDto user) {
        int integer = RegexUtil.validPhoneOrMail(user.getUsername());
        UserLoginDto   yxUsers=getYxUser(integer,user.getUsername());

        if(null==yxUsers){
            return  RespDTO.onFail("用户不存在");
        }
        if(!Util.md5(user.getPassword()).substring(0,20).equalsIgnoreCase(yxUsers.getPassword())){
            return  RespDTO.onFail("用户名或密码错误");
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String auth=null;
        try {
            auth= encoder.encode((application + ":123456").getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return  RespDTO.onFail(e.toString());
        }
        JWT jwt = authServiceClient.getToken("Basic "+auth, "password", user.getUsername(), yxUsers.getPassword());
        // 获得用户菜单
        if(null==jwt){
            return RespDTO.onFail("获取token失败，稍后重试");
        }
        LoginDTO loginDTO=new LoginDTO();
        yxUsers.setPassword("");
        loginDTO.setUser(yxUsers);
        loginDTO.setToken(jwt.getAccess_token());
        redisUtil.setSuffixKey("permission");
        redisUtil.set(user.getUsername(),yxUsers.getId(),1800);
        redisUtil.set(String.valueOf(yxUsers.getId()),jwt.getAccess_token(),1800);
        System.out.println(user.getUsername()+":"+redisUtil.getString(String.valueOf(yxUsers.getId())));

        return RespDTO.onSuc(loginDTO);

    }

    @Override
    public UserLoginDto getUserInfo(String username) {
        int integer = RegexUtil.validPhoneOrMail(username);
        UserLoginDto user=getYxUser(integer,username);
        return user;
    }










}
